import {
  deleteTopic,
  selectCuesTopicManage,
  selectTopicManageTreeAssignOrganization,
  selectTopicManageTreeLinkageOrganization,
} from '@/services/api/api-cues-topic';
import {
  CloseCircleOutlined,
  FileTextOutlined,
  LikeOutlined,
  StopOutlined,
} from '@ant-design/icons';
import { ModalForm, ProFormCascader } from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { useAccess } from '@umijs/max';
import {
  Avatar,
  Button,
  Card,
  Cascader,
  Descriptions,
  Divider,
  Flex,
  message,
  Space,
  Tag,
  theme,
  Typography,
} from 'antd';
import Meta from 'antd/es/card/Meta';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import EventHandlingProcess from '../../components/EventHandlingProcess';
import TownStreetClues from '../../components/TownStreetClues';
import ReceiptReport from '../components/ReceiptReport';
import TableTopicManageUpdate from './TableTopicManageUpdate';
import TableSubmit from './TableTopicSubmit';
interface TableTableTopicRenderDetailsProps {
  item: CuesTopicData.TopicPage;
  onRefurbish: () => void;
  title: string;
  triggerMode: 'card' | 'title';
  topicId?: string;
  type?: 'intelligent';
  brainOpen: 'progress' | 'table';
  brainOpenTopicMode: 'progress' | 'table';
}

const TableTableTopicRenderDetails: React.FC<TableTableTopicRenderDetailsProps> = ({
  item,
  onRefurbish,
  title,
  triggerMode,
  topicId,
  type,
  brainOpen,
  brainOpenTopicMode,
}) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);

  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  /**
   * 联动单位数据
   */
  const [treeLinkageOrganizationData, setTreeLinkageOrganizationDataState] = useState<DataNode[]>();

  /**
   * 选题计划详情
   */
  const [dataTopicDetails, setDataTopicDetailsState] = useState<CuesTopicData.TopicSelectManage>();

  const [drawerFormVisible, setDrawerFormVisible] = useState(false);

  /**
   * 申请记录
   */
  const { token } = theme.useToken();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadSelectTopicManageTreeAssignOrganization = async () => {
    try {
      const response = await selectTopicManageTreeAssignOrganization({ id: item.id });
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载 保存 联动 单位
   */
  const loadSelectTopicManageTreeLinkageOrganization = async () => {
    try {
      const response = await selectTopicManageTreeLinkageOrganization({
        id: item.id,
      });
      if (response.code === 0) {
        setTreeLinkageOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载 选题计划详情
   * @param key
   */
  const loadCuesTopicDetails = async () => {
    setLoading(true);
    try {
      const response = await selectCuesTopicManage({ id: item.id });
      const { code, data } = response;
      if (code === 0) {
        setDataTopicDetailsState(data);
        formRef.current?.setFieldsValue({
          deadlineTime: [data.createdTime, data.deadlineTime],
          assignOrganizationIds: data.cascaderAssignOrganizations,
          linkageOrganizationIds: data.cascaderLinkageOrganizations,
        });

        setLoading(false);
      }
    } catch (error) {}
  };
  useEffect(() => {
    console.log('========111111111111111111111=====');

    if (topicId === item.id) {
      console.log('========2222222222222222222222222=====');

      if (topicId !== undefined) {
        console.log('========33333333333333333333333333=====', brainOpen);

        if (brainOpen == brainOpenTopicMode) {
          setDrawerFormVisible(true);
        }
      }
    }
  }, [brainOpen]);
  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const IconText = ({ icon, text }: { icon: any; text: string }) => (
    <span style={{ color: '#1677FF' }}>
      {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
      {text}
    </span>
  );

  const TitleText = ({ title, text }: { title: string; text: any }) => (
    <div style={{ color: '#1677FF' }}>
      {title}：{text}
    </div>
  );

  const drawerFormView = () => {
    let cover = '';

    let gradeName = '';
    let gradeColor = '';

    if (item.grade === 1) {
      cover = 'https://wx4.sinaimg.cn/mw2000/0033ImPzly1hj076fx0z4j60p00p00w502.jpg';
      gradeName = '重大';
      gradeColor = '#f50';
    } else if (item.grade === 2) {
      cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fx3ilj60p00p0wi502.jpg';
      gradeName = '重要';
      gradeColor = '#ffd591';
    } else if (item.grade === 3) {
      cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fwx7zj60p00p0tc802.jpg';
      gradeName = '一般';
      gradeColor = '#2db7f5';
    }

    let linkageTypeName = '';

    if (item.linkageType === 1) {
      linkageTypeName = '协助';
    } else if (item.linkageType === 2) {
      linkageTypeName = '联动';
    } else if (item.linkageType === 3) {
      linkageTypeName = '协助';
    } else {
      linkageTypeName = '暂无';
    }

    let recordActions: React.JSX.Element[] | React.ReactNode[] | undefined = [];

    if (item.recordState === 1) {
      recordActions = [
        <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
        <IconText icon={StopOutlined} text="撤销" key="list-vertical-star-o" />,
        <IconText icon={LikeOutlined} text="发布" key="list-vertical-like-o" />,
        <IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />,
      ];
    } else if (item.recordState === 2) {
      recordActions = [
        <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
        <IconText icon={FileTextOutlined} text="详情" key="list-vertical-like-o" />,
      ];
    } else if (item.recordState === 3) {
      if (access.线索征集x配置x提供者 || access.线索征集x配置x区县提供者) {
        recordActions = [
          <TitleText
            key={'title_text_count_submit_organization'}
            title="报送线索"
            text={item.countSubmit}
          />,
        ];
      } else {
        recordActions = [
          <TitleText
            key={'title_text_count_submit_organization'}
            title="上报单位"
            text={item.countSubmitOrganization}
          />,
          <TitleText key={'title_text_count_submit'} title="报送线索" text={item.countSubmit} />,
        ];
      }
    } else {
      recordActions = [<IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />];
    }

    // let industryNames = item?.industryNames;

    // if (industryNames.length > 3) {
    //   industryNames = industryNames.slice(0, 3);
    //   industryNames.push('...');
    // }

    // let labelNames = item?.labelNames;

    // if (labelNames.length > 3) {
    //   labelNames = labelNames.slice(0, 3);
    //   labelNames.push('...');
    // }

    return (
      <DrawerForm
        key="add_topic_drawer_form"
        title={
          <Flex justify={'space-between'} align={'center'}>
            <div>
              <Tag color={gradeColor}>{gradeName}</Tag>
              <Tag color={item.run === 1 ? 'green' : item.run === 2 ? 'red' : 'orange'}>
                {item.run === 1 ? '进行中' : item.run === 2 ? '已结束' : '已暂停'}
              </Tag>
              {item.isLinkage === 1 && <Tag color="orange">{linkageTypeName}</Tag>}
              {dataTopicDetails?.name}
            </div>
            <div>
              <Space>
                {item.run === 1 && access.线索征集x配置x管理员 && (
                  <TableTopicManageUpdate
                    item={item}
                    onRefurbish={function (): void {
                      //加载权限树请求网络
                      loadSelectTopicManageTreeAssignOrganization();
                      loadSelectTopicManageTreeLinkageOrganization();
                      loadCuesTopicDetails();
                    }}
                  />
                )}
                {access.线索征集x配置x管理员 && (
                  <ModalForm
                    key={'modal_form_release_state_release'}
                    title={<>是否删除选题 : {item.name}</>}
                    trigger={
                      <Button type="primary" danger>
                        删除
                      </Button>
                    }
                    autoFocusFirstInput
                    modalProps={{
                      width: 400,
                      // bodyStyle: { textAlign: 'center' },
                      destroyOnClose: true,
                      onCancel: () => console.log('run'),
                    }}
                    submitTimeout={2000}
                    submitter={{
                      submitButtonProps: {
                        type: 'primary',
                        style: { background: '#FF5500' },
                      },
                    }}
                    onFinish={async (values) => {
                      const res = await deleteTopic({ id: item.id });
                      if (res.code === 0) {
                        message.success('删除成功');
                        setDrawerFormVisible(false);
                        onRefurbish();
                      }
                      return true;
                    }}
                  >
                    {item.isSubmit === 1 ? '该选题已有上报线索，是否确定删除？' : ''}
                  </ModalForm>
                )}
                {/* <Button size="middle" type="primary">
                  发起采访任务
                </Button> */}
                <Button size="middle" type="primary">
                  创作写稿
                </Button>
              </Space>
            </div>
          </Flex>
        }
        drawerProps={{
          // maskClosable: false,
          destroyOnClose: true,
          width: 1200,
        }}
        open={drawerFormVisible}
        loading={loading}
        formRef={formRef}
        trigger={
          triggerMode === 'card' ? (
            <div
              style={{
                paddingLeft: 10,
                paddingRight: 10,
                paddingBottom: 10,
              }}
            >
              <Card
                bordered={false}
                hoverable
                style={{
                  // background:
                  //   item.run === 1
                  //     ? item.grade === 1
                  //       ? 'linear-gradient(#FDDCD8,#fff,#fff)'
                  //       : item.grade === 2
                  //         ? 'linear-gradient(#FFFBE6,#fff, #fff)'
                  //         : item.grade === 3
                  //           ? 'linear-gradient(#ECF7FF,#fff, #fff)'
                  //           : '#FFF'
                  //     : '#FFF',
                  background: 'linear-gradient(#F5FBFF,#fff, #fff)',
                }}
                // cover={<img height={200} src={cover} />}
                actions={recordActions}
                bodyStyle={{
                  borderTop: '0px solid #f0f0f0',
                }}
              >
                <Meta
                  avatar={
                    <Avatar
                      style={{
                        marginTop: '2px',
                      }}
                      size={'large'}
                      src={item.createdOrganizationAvatar}
                    />
                  }
                  title={
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <div
                        style={{
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          minWidth: 65,
                        }}
                      >
                        {item.createdOrganizationName}
                      </div>
                      <div
                        style={{
                          float: 'right',
                        }}
                      >
                        <Tag color={gradeColor}>{gradeName}</Tag>
                        {item.isLinkage === 1 && <Tag color="orange">{linkageTypeName}</Tag>}
                        <Tag color={item.run === 1 ? 'green' : item.run === 2 ? 'red' : 'orange'}>
                          {item.run === 1 ? '进行中' : item.run === 2 ? '已结束' : '已暂停'}
                        </Tag>
                        {item.showView === 1 && item.isView === 0 ? (
                          <Tag color="red">未阅读</Tag>
                        ) : item.showSubmit === 1 && item.isSubmit === 0 ? (
                          <Tag color="red">未上报</Tag>
                        ) : (
                          <></>
                        )}
                      </div>
                    </div>
                  }
                  description={
                    <>
                      <Typography.Paragraph ellipsis={true}>
                        {
                          <span
                            style={{
                              color: token.colorTextDescription,
                              fontSize: 15,
                            }}
                          >
                            {item.name}
                          </span>
                        }
                      </Typography.Paragraph>
                      {/* <div>
                        行业：
                        <Space size={[0, 8]} wrap>
                          {industryNames?.map((item) => (
                            <Tag key={item}>{item}</Tag>
                          ))}
                        </Space>
                      </div>
                      <div
                        style={{
                          marginTop: 5,
                        }}
                      >
                        标签：
                        <Space size={[0, 8]} wrap>
                          {labelNames.slice(0, 3).map((item, index) => (
                            <Tag key={index}>
                              <div
                                style={{
                                  whiteSpace: 'nowrap',
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis',
                                  maxWidth: 60,
                                }}
                              >
                                {item}
                              </div>
                            </Tag>
                          ))}
                          {labelNames.length > 3 ? <Tag>...</Tag> : ''}
                        </Space>
                      </div> */}
                      <div
                        style={{
                          marginTop: 5,
                          marginRight: 18,
                        }}
                      >
                        <span
                          style={{
                            color:
                              item.run === 1
                                ? '#F47983'
                                : item.run === 2
                                ? token.colorTextDescription
                                : 'orange',
                          }}
                        >
                          截至：
                          {item.deadlineTime.slice(0, 11)}
                        </span>
                        <span
                          style={{
                            float: 'right',
                          }}
                        >
                          {moment(item.createdTime).fromNow()}
                        </span>
                      </div>
                    </>
                  }
                />
              </Card>
              <div
                style={{
                  borderRadius: 12,
                  background: '#FFF',
                  // backgroundImage: 'url(https://www.freeimg.cn/i/2023/10/24/6537c64da6294.png) no-repeat',
                }}
              >
                {/* <Badge.Ribbon text={gradeName} color={gradeColor} placement="start">
              </Badge.Ribbon> */}
              </div>
            </div>
          ) : (
            <a>{title}</a>
          )
        }
        initialValues={{}}
        onOpenChange={(visible: boolean) => {
          if (visible) {
            //加载权限树请求网络
            loadSelectTopicManageTreeAssignOrganization();
            loadSelectTopicManageTreeLinkageOrganization();
            loadCuesTopicDetails();
          } else {
            onRefurbish();
          }
          setDrawerFormVisible(visible);
        }}
        onValuesChange={(values) => {
          if (values.assignOrganizationIds !== undefined) {
            formRef.current?.setFieldsValue({
              assignOrganizationIds: dataTopicDetails?.cascaderAssignOrganizations,
            });
          }
          if (values.linkageOrganizationIds !== undefined) {
            formRef.current?.setFieldsValue({
              linkageOrganizationIds: dataTopicDetails?.cascaderLinkageOrganizations,
            });
          }
          if (values.deadlineTime !== undefined) {
            formRef.current?.setFieldsValue({
              deadlineTime: [dataTopicDetails?.createdTime, dataTopicDetails?.deadlineTime],
            });
          }
        }}
        submitter={false}
        onFinish={async (values) => {}}
      >
        <Descriptions size="small">
          <Descriptions.Item label="单位">
            {/* <Avatar size="small"></Avatar> */}
            {dataTopicDetails?.createdOrganizationName}
          </Descriptions.Item>
          <Descriptions.Item label="创建人">
            {dataTopicDetails?.createdAccountName}
          </Descriptions.Item>
          {type !== 'intelligent' && (
            <Descriptions.Item label="联系方式">
              {dataTopicDetails?.createdAccountPhone}
            </Descriptions.Item>
          )}
        </Descriptions>
        {/* <Descriptions
          size="small"
          style={{
            marginTop: 24,
          }}
        >
          <Descriptions.Item label="行业">
            <Space size={[0, 8]} wrap>
              {dataTopicDetails?.industryNames.map((industry) => (
                <Tag key={item.id + industry}>{industry}</Tag>
              ))}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="标签">
            <Space size={[0, 8]} wrap>
              {item.labelNames.map((label) => (
                <Tag key={item.id + label}>{label}</Tag>
              ))}
            </Space>
          </Descriptions.Item>
        </Descriptions> */}
        <Descriptions
          size="small"
          style={{
            marginTop: 24,
          }}
        >
          <Descriptions.Item label="创建日期">
            <Typography.Text type="success">{dataTopicDetails?.createdTime}</Typography.Text>
          </Descriptions.Item>
          <Descriptions.Item label="截止日期">
            <Typography.Text type="danger">{dataTopicDetails?.deadlineTime}</Typography.Text>
          </Descriptions.Item>

          {access.线索征集x配置x管理员 && (
            <Descriptions.Item label="阅读情况">
              <ReceiptReport
                id={dataTopicDetails?.id}
                receipt={dataTopicDetails?.receipt}
                onRefurbish={() => {
                  onRefurbish();
                }}
              />
            </Descriptions.Item>
          )}
        </Descriptions>
        <Descriptions
          size="small"
          style={{
            marginTop: 24,
          }}
        >
          <Descriptions.Item>
            <TownStreetClues id={dataTopicDetails?.id} />
          </Descriptions.Item>
          <Descriptions.Item>
            {access.线索征集x配置x管理员 && dataTopicDetails?.eventNum && (
              <EventHandlingProcess id={dataTopicDetails?.id} />
            )}
          </Descriptions.Item>
        </Descriptions>
        {/* <div style={{marginTop:20}}>
          {access.线索征集x配置x管理员 && dataTopicDetails?.eventNum && (
            <EventHandlingProcess id={dataTopicDetails?.id} />
          )}
            {access.线索征集x配置x管理员 && dataTopicDetails?.eventNum && (
            <TownStreetClues id={dataTopicDetails?.id} />
          )}
        </div> */}
        <div>
          <ProFormCascader
            width="xl"
            label={
              <span
                style={{
                  color: 'rgba(0, 0, 0, 0.45)',
                }}
              >
                邀请采访单位：
              </span>
            }
            name="assignOrganizationIds"
            placeholder="选择单位"
            fieldProps={{
              options: treeAssignOrganizationData,
              showSearch: { filter },
              multiple: true,
              removeIcon: false,
              allowClear: false,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_CHILD,
            }}
          />
        </div>
        <div
          style={{
            marginTop: 24,
          }}
        >
          <span
            style={{
              color: 'rgba(0, 0, 0, 0.45)',
            }}
          >
            选题内容：
          </span>
          <Typography.Paragraph>
            <blockquote>{dataTopicDetails?.content}</blockquote>
          </Typography.Paragraph>
        </div>

        {dataTopicDetails?.isLinkage === 1 && dataTopicDetails?.cascaderLinkageOrganizations && (
          <>
            <Divider />
            <ProFormCascader
              width="xl"
              label={
                <span
                  style={{
                    color: 'rgba(0, 0, 0, 0.45)',
                  }}
                >
                  {dataTopicDetails?.linkageType === 1
                    ? '协助媒体'
                    : dataTopicDetails?.linkageType === 2
                    ? '联动部门'
                    : dataTopicDetails?.linkageType === 3
                    ? '协助媒体、单位'
                    : '协助媒体、单位'}
                  ：
                </span>
              }
              name="linkageOrganizationIds"
              placeholder="选择单位"
              fieldProps={{
                options: treeLinkageOrganizationData,
                showSearch: { filter },
                multiple: true,
                removeIcon: false,
                allowClear: false,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
              }}
            />
            {dataTopicDetails?.linkageDescribes && (
              <div
                style={{
                  marginTop: 8,
                  color: 'rgba(0, 0, 0, 0.45)',
                }}
              >
                {dataTopicDetails?.linkageType === 1
                  ? '协助媒体描述'
                  : dataTopicDetails?.linkageType === 2
                  ? '联动部门描述'
                  : dataTopicDetails?.linkageType === 3
                  ? '协助媒体、单位描述'
                  : '协助媒体、单位描述'}
                ：
                <Typography.Paragraph>
                  <blockquote>{dataTopicDetails?.linkageDescribes}</blockquote>
                </Typography.Paragraph>
              </div>
            )}
          </>
        )}

        <TableSubmit
          mode={1} //开放页面
          item={item}
          onRefurbish={function (): void {
            onRefurbish();
          }}
        />
      </DrawerForm>
    );
  };

  return drawerFormView();
};
export default TableTableTopicRenderDetails;
